package ca.starfarer.kobold.dao.sqlite;

import ca.starfarer.kobold.dao.DataAccessException;
import ca.starfarer.kobold.dao.MonsterDAO;
import ca.starfarer.kobold.dao.DAOManager;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Kevin
 */
public class SQLiteDAOManager extends DAOManager {

    static {
        // Load the SQLite JDBC driver
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            throw new NoClassDefFoundError(e.getMessage());
        }
    }

    private final Connection connection;

    private final MonsterDAOImpl monsterDAO;

    public SQLiteDAOManager(String filename) throws DataAccessException {
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:" + filename);
        } catch (SQLException e) {
            throw new DataAccessException("Cannot open " + filename, e);
        }

        monsterDAO = new MonsterDAOImpl(this);
    }

    Connection getConnection() {
        return connection;
    }

    @Override
    public void initializeDB() throws DataAccessException {
        try {
            monsterDAO.createTable();
        } catch (SQLException e) {
            throw new DataAccessException("Unable to initialize database", e);
        }
    }

    @Override
    public MonsterDAO getMonsterDAO() {
        return monsterDAO;
    }
}
